<template>
    <div class="forum-editor">
        <!-- 工具栏区域 - 只显示当前焦点编辑器对应的工具栏 -->
        <div v-for="item in editorList" :key="'toolbar-'+item.index">
            <Toolbar 
                v-show="showEditorIndex === item.index"
                :editor="editorRefs[item.index - 1]?.value" 
                :defaultConfig="item['toolbarConfig'+item.index]"
                :mode="item['mode'+item.index]" 
            />
        </div>
        
        <!-- 编辑器内容区域 -->
        <div class="editor-content">
            <div v-for="item in editorList" :key="'editor-'+item.index" class="editor-item">
                <Editor 
                    :style="getEditorStyle(item.index)"
                    v-model="item['html'+item.index]" 
                    :defaultConfig="item['editorConfig'+item.index]"
                    :mode="item['mode'+item.index]" 
                    @onCreated="(editor) => handleCreated(item.index - 1, editor)" 
                    @onChange="handleChange" 
                    @onFocus="() => handleFocus(item)" 
                    @onBlur="handleBlur" 
                />
            </div>
        </div>
    </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef } from 'vue'
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"

const editorTitleContent = ref({
    title: '',
    content: ''
})

// 当前显示的编辑器工具栏索引
const showEditorIndex = ref(1)

// 当前活动的编辑器项索引
const activeEditorIndex = ref(0)

// 编辑器实例列表，必须用 shallowRef
const editorRefs = [
    shallowRef(null), // 标题编辑器
    shallowRef(null)  // 正文编辑器
]

// 编辑器列表配置
const editorList = ref([
    {
        index: 1,
        title1: '标题',
        html1: '',
        editorConfig1: { 
            placeholder: '标题',
            autoFocus: true
        },
        mode1: 'default',
        toolbarConfig1: {
            // excludeKeys: [
            //     'group-video',
            //     'insertTable',
            //     'codeBlock',
            //     'todo',
            //     'group-image',
            //     'group-more-style',
            //     'insertLink'
            // ]
        }
    },
    {
        index: 2,
        title2: '正文',
        html2: '',
        editorConfig2: { 
            placeholder: '请输入正文内容...'
        },
        mode2: 'default',
        toolbarConfig2: {}
    }
])

// 根据索引获取编辑器样式
const getEditorStyle = (index) => {
    if (index === 1) {
        return {
            height: '49px',
            overflowY: 'hidden'
        }
    } else {
        return {
            height: '400px', 
            overflowY: 'auto', 
        }
    }
}

// 创建编辑器时的回调 - 使用shallowRef存储编辑器实例
const handleCreated = (index, editor) => {
    // 直接将编辑器实例存储在shallowRef中
    editorRefs[index].value = editor
    console.log(`${editorList.value[index]['title'+(index+1)]} 编辑器创建成功`)
}

// 编辑器内容变化
const handleChange = (editor) => {
    console.log('内容变化', editor.getHtml())
    // console.log(activeEditorIndex.value, 'activeEditorIndex')
    // const allContent = editor.getHtml();
    // const title = activeEditorIndex.value === 1 && allContent;
    // const maincontent = activeEditorIndex.value === 0 && allContent;
    // editorTitleContent.value.title = title;
    // editorTitleContent.value.content = maincontent;
}

// 编辑器获取焦点
const handleFocus = (item) => {
    // 更新当前活动的编辑器索引
    activeEditorIndex.value = item.index - 1
    // 显示对应的工具栏
    showEditorIndex.value = item.index
    console.log(`${item['title'+item.index]} 获取焦点`)
}

// 编辑器失去焦点
const handleBlur = (editor) => {
    console.log('失去焦点', editor)
}

// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
    editorRefs.forEach(editorRef => {
        const editor = editorRef.value
        if (editor != null) {
            editor.destroy()
        }
    })
})

// 计算总字数
const getTotalWords = () => {
    let totalCount = 0
    editorList.value.forEach(item => {
        const content = item['html' + item.index]?.replace(/<[^>]+>/g, '').trim() || ''
        totalCount += content.length
    })
    return totalCount
}

// 向外部暴露的方法和数据
defineExpose({
    editorList,
    editorRefs,
    getTotalWords,
    // 获取标题内容
    getTitleContent: () => editorList.value[0].html1,
    // 获取正文内容
    getContentBody: () => editorList.value[1].html2
})
</script>

<style scoped lang="scss">
.forum-editor {
    width: 100%;
    border-radius: 8px;
    
    .editor-content {
        // background-color: #fff;
        width: 100%;
        border-radius: 4px;
        margin-top: 10px;
        .editor-item {
        }
    }
}
</style>